#!/usr/bin/python -S

import os
import sys
import commands


program_name = sys.argv[1]

candidates = sorted([x.strip() for x in commands.getoutput(""" wmctrl -l -x | awk -v win="%s" 'tolower($0) ~ win {print $1;}' """ % (program_name, )).split("\n") if x !=''])

out_file = file("/home/soma/debug.txt", "a")
print candidates
if candidates :
	active_window_string = commands.getoutput("""xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)" """)
	active_window_string =  active_window_string[active_window_string.find("#")+4:].strip()
	active_window = "0x" + "0" * (8-len(active_window_string)) + active_window_string

	out_file.write("\n")
	out_file.write(",".join(candidates))
	out_file.write("\n")
	out_file.write( active_window)
	out_file.write("\n")

	next_window = None
	if active_window not in candidates:
		out_file.write("Not In")
		next_window = candidates[0]
	else:
		out_file.write("In")
		next_window = candidates[ (candidates.index(active_window)+1) % len(candidates)]

	os.system(""" wmctrl -i -a "%s" """ % (next_window,) )
else :
    out_file.write("Starting") 
    os.system("%s &" % (program_name,))

out_file.close()
